<?php

namespace App\Http\Logic\Admin;

use App;
use App\Common\Status;
use App\Helper\Helper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdminLogic
{
    /**
     * @param $params
     * @param $pageSize
     * @param $page
     * @return array
     */
    public static function getAdminList($params,$pageSize, $page)
    {
        $where[] = ['is_deleted', '=', Status::NOT_DELETE];
        $where[] = ['status', '=', Status::REGULAR];

        if($params['type'] == 2) {
            $data  = DB::table('recruit_admin_user')
                ->select(['id','username'])
                ->where($where)
                ->orderBy("created_at", "desc")
                ->get();
            return ['list' => $data];
        }
        $data  = DB::table('recruit_admin_user')
            ->where($where)
            ->orderBy("created_at", "desc")
            ->offset($pageSize * ($page - 1))
            ->limit($pageSize)
            ->get();
        $count = self::getCount($where);

        return ['list' => $data, 'total' => $count, 'page' => $page, 'pageSize' => $pageSize];

    }

    private static function getCount($where)
    {
        return DB::table('recruit_admin_user')
            ->where($where)
            ->count();
    }


    /**
     * @param $params
     * @return mixed
     * @throws \Exception
     */
    public static function createAdmin($params)
    {
        $pwd = $params['password'];
        unset($params['password']);
        $params['password'] = Hash::make($pwd);
        if (isset($params['id']) && $params['id']) {
            $id = $params['id'];

            $params['updated_at'] = time();

            unset($params['id']);

            DB::table('recruit_admin_user')->where('id', $id)->update($params);
            return true;
        }

        $params['created_at'] = time();

        $params['creator_id'] = Helper::adminById();

        $id = DB::table('recruit_admin_user')->insertGetId($params);

        return $id;
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    public function getAdminDtl($id)
    {
        return DB::table('recruit_admin_user')->find($id);
    }


    /**
     * @param $id
     * @return mixed
     */
    public static function delAdmin($id)
    {
        return DB::table('recruit_admin_user')->where('id',$id)->update(
            [
                'status' => Status::NOT_DELETE,
                'is_deleted' => Status::DELETED,
                'deleted_at' => time()
            ]
        );
    }
}
